package com.j;

import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;
import org.apache.catalina.websocket.WsOutbound;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;

/**
 * 这个是旧的方式 而且这个没有请求成功 尚不知道什么原因
 * Created by zhuangjianhui_91 on 2015/10/27.
 */
@WebServlet(urlPatterns = { "/wsServlet"})
public class WebSocketDemo extends WebSocketServlet {

	private static final long serialVersionUID = -4853540828121130946L;
	private static ArrayList<MyMessageInbound> mmiList = new ArrayList<>();

		
	@Override
	public void init() throws ServletException {
		super.init();
		System.out.println("初始化。。。。。。。。。。。");
	}


	@Override 
	protected StreamInbound createWebSocketInbound(String s) {
		System.out.println("createWebSocketInbound");
		return new MyMessageInbound();
	}


	private class MyMessageInbound extends MessageInbound {

		WsOutbound myoutbound;


		@Override
		public void onOpen(WsOutbound outbound) {
			try {
				System.out.println("Open Client.");
				this.myoutbound = outbound;
				mmiList.add(this);
				outbound.writeTextMessage(CharBuffer.wrap("Hello!"));

			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onClose(int status) {
			System.out.println("Close Client.");
			mmiList.remove(this);
		}

		@Override
		public void onTextMessage(CharBuffer cb) throws IOException {
			System.out.println("Accept Message : " + cb);
			for (MyMessageInbound mmib : mmiList) {
				CharBuffer buffer = CharBuffer.wrap(cb);
				mmib.myoutbound.writeTextMessage(buffer);
				mmib.myoutbound.flush();
			}
		}

		@Override
		public void onBinaryMessage(ByteBuffer bb) throws IOException {
		}



		@Override
		public int getReadTimeout() {
			return 300000;
		}
		
	}
}
